package controllers;

import helpers.GeneralHelper;
import helpers.PaginatorHelper;
import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import quercus.CompileScriptEngine;

import systems.Recently;
import systems.RecentlyTag;

import debugs.ArticleDebug;

import entities.ApplicationConfig;
import entities.ApplicationTemplate;
import entities.Article;
import entities.Category;
import entities.SeoData;
import entities.User;

import models.ArticleModel;
import models.CategoryModel;
import models.UserModel;

public class CategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		ApplicationTemplate appTemplate = (ApplicationTemplate) request.getAttribute("sysTemplate");
		
		if (appTemplate == null) {
			response.getWriter().println("Please enter template");
			return ;
		}
		
		Cache memCache = GeneralHelper.getCache();
		
		User user = (User) request.getAttribute("user_logged_in");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String alias = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Category category = categoryModel.getCategoryByAlias(appConfig.getApplicationId(), alias);
		
		if (category == null) {
			response.sendRedirect("/msg/page-not-found");
			return ;
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		//Get article by category and paginator
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		boolean nextPage = false;
		boolean prevPage = false;
		int limit = 20;
		
		
		ArticleModel articleModel = ArticleModel.getInstance();
		List<Article> articles = Recently.getArticles(appConfig.getApplicationId(), category.getId(), "category");
		
		if (page > 1) {
			articles = articleModel.listByCategory(appConfig.getApplicationId(), category.getId(), page, limit, language);
		} else {
			List<Article> lsArticles = articleModel.listByCategory(appConfig.getApplicationId(), category.getId(), page, limit, language);
			if (articles.size() == 0 || articles.size() < lsArticles.size()) {
				for (int i = lsArticles.size() - 1; i >= 0; i--) {
					Recently.insertArticle(appConfig.getApplicationId(), category.getId(), "category", lsArticles.get(i));
				}
				articles = Recently.getArticles(appConfig.getApplicationId(), category.getId(), "category");
			}
		}
		
		
		
		if (articles.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		//Get categories
		List<String> uIds = new ArrayList<String>();
		
		for (int i = 0; i < articles.size(); i++) {
			if (!articles.get(i).getCreator().isEmpty()) {
				uIds.add(articles.get(i).getCreator());
			}
		}
		
		UserModel userModel = UserModel.getInstance();
		Map<String, User> authors = userModel.getByListId(appConfig.getApplicationId(), uIds);
		
		//Get list category
		List<Category> lstCategories = categoryModel.getAll(appConfig.getApplicationId());
		
		//Get tags
		List<String> tags = RecentlyTag.getTags(appConfig.getApplicationId());
		
		//Get Seo Data 
		SeoData seoData = new SeoData();
		
		/******************************Set page template ******************************/
		String layout_for_content = "";
		String layout_for_header = "";
		String layout_for_footer = "";
		
		String cacheLayoutName = appConfig.getApplicationId() + "_layout";
		String cacheHeaderName = appConfig.getApplicationId() + "_header";
		String cacheFooterName = appConfig.getApplicationId() + "_footer";
		String cacheContentName = appConfig.getApplicationId() + "_category_" + alias;
		
		layout_for_content = (String) memCache.get(cacheContentName);
		if (layout_for_content == null) {
			//String contentPage = StringHelper.getContentPhp("/templates/classic/category.php", getServletContext());
			String contentPage = appTemplate.getCategory();
			String library = appTemplate.getLibrary();
			CompiledScript compiledContent = CompileScriptEngine.getCompileScript(appConfig.getApplicationId(), "layout_for_content", contentPage);
			
			//Set value
			if (compiledContent != null) {
				Bindings bind = compiledContent.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
				bind.put("category", category);
				bind.put("articles", articles);
				bind.put("authors", authors);
				bind.put("paginator", paginator);
				bind.put("prevPage", prevPage);
				bind.put("nextPage", nextPage);
				bind.put("pages", page);
				bind.put("lstCategories", lstCategories);
				bind.put("tags", tags);
				bind.put("user", user);
				bind.put("baseUrl", appTemplate.getBaseUrl());
				bind.put("library", library);
				bind.put("seoData", seoData);
			}
			
			try {
				layout_for_content = (String) compiledContent.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}

			memCache.put(cacheContentName, layout_for_content);
		} 
		
		layout_for_header = (String) memCache.get(cacheHeaderName);
		if (layout_for_header == null) {
			//String headerPage = StringHelper.getContentPhp("/templates/classic/header.php", getServletContext());
			String headerPage = appTemplate.getHeader();
			CompiledScript compiledHeader = CompileScriptEngine.getCompileScript(appConfig.getApplicationId(), "layout_for_header", headerPage);
			try {
				layout_for_header = (String) compiledHeader.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheHeaderName, layout_for_header);
		}
		
		
		layout_for_footer = (String) memCache.get(cacheFooterName);
		if (layout_for_footer == null) {
			//String footerPage = StringHelper.getContentPhp("/templates/classic/footer.php", getServletContext());
			String footerPage = appTemplate.getFooter();
			CompiledScript compiledFooter = CompileScriptEngine.getCompileScript(appConfig.getApplicationId(), "layout_for_footer", footerPage);
			try {
				layout_for_footer = (String) compiledFooter.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheFooterName, layout_for_footer);
		}
		
		String layoutPage = (String) memCache.get(cacheLayoutName);
		if (layoutPage == null) {
			//layoutPage = StringHelper.getContentPhp("/templates/classic/layouts.php", getServletContext());
			layoutPage = appTemplate.getLayout();
			memCache.put(cacheLayoutName, layoutPage);
		}
		
		layoutPage = layoutPage.replace("$layout_for_header", layout_for_header);
		layoutPage = layoutPage.replace("$layout_for_content", layout_for_content);
		layoutPage = layoutPage.replace("$layout_for_footer", layout_for_footer);
		layoutPage = layoutPage.replace("__META_TITLE__", seoData.getTitle());
		layoutPage = layoutPage.replace("__META_DESCRIPTION__", seoData.getDescription());
		layoutPage = layoutPage.replace("__META_KEYWORD__", seoData.getKeywords());
		layoutPage = layoutPage.replace("__OG_SITE_NAME__", seoData.getOgSiteName() == null ? "localhost:8888" : seoData.getOgSiteName());
		layoutPage = layoutPage.replace("__OG_TITLE__", seoData.getOgTitle());
		layoutPage = layoutPage.replace("__OG_DESCRIPTION__", seoData.getOgDescription());
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		try {
			response.getWriter().print(layoutPage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
